const app = getApp();

Page({
    data: {
      userId: null,
      searchKey: '',
      categories: [],
      files: [],
      currentCategoryId: null,
      showCategoryModal: false,
      showFileModal: false,
      categoryForm: { id: null, name: '', description: '' },
      fileForm: { name: '', filePath: '' },
      isEditCategory: false,
      isCategoryView: true, // true: 分类列表，false: 文件列表
      emptyStateImage: 'https://ai-public.mastergo.com/ai/img_res/81af315b17e254a7741660615058b89e.jpg'
    },
  
    onLoad() {
      // 获取用户ID
      const userInfo = wx.getStorageSync('userInfo');
      if (!userInfo || !userInfo.id) {
        wx.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
      this.setData({ userId: userInfo.id });
      this.loadCategories();
    },
  
    // 分类相关
    loadCategories() {
      wx.request({
        url: app.globalData.baseUrl + '/api/cloud/category/list',
        method: 'GET',
        data: { userId: this.data.userId, keyword: this.data.searchKey },
        success: res => {
          if (res.data.code === 200) {
            this.setData({ categories: res.data.data.list, isCategoryView: true });
          }
        }
      });
    },
  
    showAddCategory() {
      this.setData({ showCategoryModal: true, isEditCategory: false, categoryForm: { id: null, name: '', description: '' } });
    },
  
    showEditCategory(e) {
      const category = e.currentTarget.dataset.item;
      this.setData({ showCategoryModal: true, isEditCategory: true, categoryForm: { ...category } });
    },
  
    handleCategoryName(e) {
      this.setData({ 'categoryForm.name': e.detail.value });
    },
  
    handleCategoryDesc(e) {
      this.setData({ 'categoryForm.description': e.detail.value });
    },
  
    submitCategory() {
      const { id, name, description } = this.data.categoryForm;
      if (!name) {
        wx.showToast({ title: '请输入分区名称', icon: 'none' });
        return;
      }
      if (this.data.isEditCategory) {
        wx.request({
          url: app.globalData.baseUrl + '/api/cloud/category/update',
          method: 'PUT',
          data: { id, userId: this.data.userId, name, description },
          success: res => {
            if (res.data.code === 200) {
              this.setData({ showCategoryModal: false });
              this.loadCategories();
              wx.showToast({ title: '修改成功', icon: 'success' });
            }
          }
        });
      } else {
        wx.request({
          url: app.globalData.baseUrl + '/api/cloud/category/create',
          method: 'POST',
          data: { userId: this.data.userId, name, description },
          success: res => {
            if (res.data.code === 200) {
              this.setData({ showCategoryModal: false });
              this.loadCategories();
              wx.showToast({ title: '创建成功', icon: 'success' });
            }
          }
        });
      }
    },
  
    deleteCategory(e) {
      const id = e.currentTarget.dataset.id;
      wx.showModal({
        title: '提示',
        content: '确定删除该分区及其下所有文件吗？',
        success: res => {
          if (res.confirm) {
            wx.request({
              url: app.globalData.baseUrl + `/api/cloud/category/delete/${id}`,
              method: 'DELETE',
              data: { userId: this.data.userId },
              success: res2 => {
                if (res2.data.code === 200) {
                  this.loadCategories();
                  wx.showToast({ title: '删除成功', icon: 'success' });
                }
              }
            });
          }
        }
      });
    },
  
    // 查看分区下文件
    viewFiles(e) {
      const category = e.currentTarget.dataset.item;
      this.setData({ currentCategoryId: category.id, isCategoryView: false });
      this.loadFiles(category.id);
    },
  
    // 文件相关
    loadFiles(categoryId) {
      wx.request({
        url: app.globalData.baseUrl + '/api/cloud/resource/list',
        method: 'GET',
        data: { userId: this.data.userId, categoryId },
        success: res => {
          if (res.data.code === 200) {
            this.setData({ files: res.data.data.list });
          }
        }
      });
    },
  
    showAddFile() {
      if (!this.data.currentCategoryId) {
        wx.showToast({ title: '请先选择分区', icon: 'none' });
        return;
      }
      this.setData({ showFileModal: true, fileForm: { name: '', filePath: '' } });
    },
  
    handleFileName(e) {
      this.setData({ 'fileForm.name': e.detail.value });
    },
  
    chooseFile() {
      wx.chooseMessageFile({
        count: 1,
        success: res => {
          this.setData({ 'fileForm.filePath': res.tempFiles[0].path });
        },
        fail: () => {
          // 兼容部分平台/模拟器不支持chooseMessageFile，降级为chooseImage
          wx.chooseImage({
            count: 1,
            success: imgRes => {
              this.setData({ 'fileForm.filePath': imgRes.tempFilePaths[0] });
            }
          });
        }
      });
    },
  
    submitFile() {
      const { name, filePath } = this.data.fileForm;
      if (!filePath) {
        wx.showToast({ title: '请选择文件', icon: 'none' });
        return;
      }
      wx.uploadFile({
        url: app.globalData.baseUrl + '/api/cloud/resource/upload',
        filePath,
        name: 'file',
        formData: {
          userId: this.data.userId,
          categoryId: this.data.currentCategoryId,
          name
        },
        success: res => {
          const result = JSON.parse(res.data);
          if (result.code === 200) {
            this.setData({ showFileModal: false });
            this.loadFiles(this.data.currentCategoryId);
            wx.showToast({ title: '上传成功', icon: 'success' });
          }
        }
      });
    },
  
    deleteFile(e) {
      const id = e.currentTarget.dataset.id;
      wx.showModal({
        title: '提示',
        content: '确定删除该文件吗？',
        success: res => {
          if (res.confirm) {
            wx.request({
              url: app.globalData.baseUrl + `/api/cloud/resource/delete/${id}`,
              method: 'DELETE',
              data: { userId: this.data.userId },
              success: res2 => {
                if (res2.data.code === 200) {
                  this.loadFiles(this.data.currentCategoryId);
                  wx.showToast({ title: '删除成功', icon: 'success' });
                }
              }
            });
          }
        }
      });
    },
  
    backToCategory() {
      this.setData({ isCategoryView: true, currentCategoryId: null, files: [] });
    },
  
    // 弹窗关闭
    closeCategoryModal() {
      this.setData({ showCategoryModal: false });
    },
  
    closeFileModal() {
      this.setData({ showFileModal: false });
    },
  
    // 搜索
    onSearchInput(e) {
      this.setData({ searchKey: e.detail.value });
    },
  
    handleSearch() {
      if (this.data.isCategoryView) {
        this.loadCategories();
      } else {
        this.loadFiles(this.data.currentCategoryId);
      }
    }
  });
  